<template>
  <el-dialog
      v-model="visible"
      title="编辑个人信息"
      width="600px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="头像">
        <div class="avatar-upload">
          <div class="avatar-preview">
            <img
                :src="form.avatar || '/default-avatar.png'"
                alt="头像"
                class="avatar"
            />
          </div>
          <div class="avatar-actions">
            <el-upload
                :before-upload="beforeAvatarUpload"
                :http-request="uploadAvatar"
                :show-file-list="false"
                accept="image/*"
            >
              <el-button size="small" type="primary">
                更换头像
              </el-button>
            </el-upload>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input
            v-model="form.nickname"
            maxlength="50"
            placeholder="请输入昵称"
            show-word-limit
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
            v-model="form.email"
            placeholder="请输入邮箱"
            type="email"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="form.phone"
            maxlength="11"
            placeholder="请输入手机号"
        />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio :label="0">未知</el-radio>
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="生日" prop="birthday">
        <el-date-picker
            v-model="form.birthday"
            format="YYYY-MM-DD"
            placeholder="请选择生日"
            style="width: 100%"
            type="date"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            :loading="loading"
            type="primary"
            @click="handleSubmit"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {updateUserProfile} from '@/api/user'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  userInfo: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// 响应式数据
const formRef = ref()
const loading = ref(false)

const form = reactive({
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  gender: 0,
  birthday: ''
})

const rules = {
  nickname: [
    {max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur'}
  ],
  email: [
    {type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur'}
  ],
  phone: [
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听用户信息变化，初始化表单
watch(() => props.userInfo, (newUserInfo) => {
  if (newUserInfo && Object.keys(newUserInfo).length > 0) {
    Object.assign(form, {
      nickname: newUserInfo.nickname || '',
      email: newUserInfo.email || '',
      phone: newUserInfo.phone || '',
      avatar: newUserInfo.avatar || '',
      gender: newUserInfo.gender || 0,
      birthday: newUserInfo.birthday || ''
    })
  }
}, {immediate: true, deep: true})

// 方法
const handleClose = () => {
  visible.value = false
  resetForm()
}

const resetForm = () => {
  formRef.value?.clearValidate()
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const uploadAvatar = async ({file}) => {
  try {
    // 将文件转换为Base64
    const base64 = await fileToBase64(file)
    form.avatar = base64
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
  }
}

const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    loading.value = true

    await updateUserProfile(form)

    emit('success')
    handleClose()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新个人信息失败:', error)
      ElMessage.error('更新个人信息失败，请重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-preview {
  width: 80px;
  height: 80px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}

.dialog-footer {
  text-align: right;
}
</style>
